package com.shop.user.config;

import com.shop.user.listener.ShortMessageListener;
import com.shop.user.utils.RunTimeUtil;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.MessageListener;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RocketMQConfig {

    @Bean
    public DefaultMQProducer defaultMQProducer() throws MQClientException {
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer();
        defaultMQProducer.setProducerGroup("short-msg-provider-group");
        defaultMQProducer.setInstanceName(RunTimeUtil.getRocketMqUniqeInstanceName());
        defaultMQProducer.setNamesrvAddr("120.24.187.139:9876");
        defaultMQProducer.start();
        return defaultMQProducer;
    }

    @Bean(initMethod = "start",destroyMethod = "shutdown")
    public DefaultMQPushConsumer defaultMQPushConsumer(){
        Map<String, String> map = new HashMap<>();
        // 消费者监听主题为Topic-Mobile-Message的消息
        map.put("Topic-Mobile-Message", "*");
        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer();
        defaultMQPushConsumer.setMessageModel(MessageModel.CLUSTERING);
        defaultMQPushConsumer.setConsumeMessageBatchMaxSize(2);
        defaultMQPushConsumer.setConsumerGroup("short-msg-consumer-group");
        defaultMQPushConsumer.setNamesrvAddr("120.24.187.139:9876");
        defaultMQPushConsumer.setMessageListener(shortMessageListener());
        defaultMQPushConsumer.setSubscription(map);
        return defaultMQPushConsumer;
    }

    @Bean
    public MessageListener shortMessageListener(){
        return new ShortMessageListener();
    }
}
